package com.jstyle.jclife.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.jstyle.blesdk.Util.SingleDealData;
import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.blesdk.constant.DeviceKey;
import com.jstyle.blesdk.model.Clock;
import com.jstyle.blesdk.model.DeviceBean;
import com.jstyle.blesdk.model.GetData;
import com.jstyle.jclife.R;
import com.jstyle.jclife.adapter.ClockAdapter;
import com.jstyle.jclife.utils.ScreenUtils;
import com.jstyle.jclife.utils.Utils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ClockListActivity extends BaseActivity implements ClockAdapter.onClockItemClickListener {

    @BindView(R.id.RecyclerView_clock_setting)
    RecyclerView RecyclerViewClockSetting;
    @BindArray(R.array.clock_array)
    String[] clockArray;
    @BindView(R.id.bt_goal_back)
    Button btGoalBack;
    @BindView(R.id.iv_back)
    Button ivBack;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    private int REQUEST_Clock = 2;
    private List<Map<String, String>> list = new ArrayList<>();
    private ClockAdapter clockAdapter;
    @BindArray(R.array.week)
    String[] weekArray;
    public static final String KEY_CLOCK_LIST = "CLOCK_LIST";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clock_setting);
        ButterKnife.bind(this);
        init();
        getClockData();
    }

    private void getClockData() {
        clockAdapter.clear();
        GetData getData = new GetData();
        sendData(SendCmdState.GET_ALARM, getData);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void init() {
        btGoalBack.setText(getString(R.string.Alarm_Setting));
        ScreenUtils.setTitleTypeface(btGoalBack);

        ivShare.setImageResource(R.drawable.iv_add_clock);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        clockAdapter = new ClockAdapter(clockArray, new ArrayList<Clock>(), this);
        ((DefaultItemAnimator)RecyclerViewClockSetting.getItemAnimator()).setSupportsChangeAnimations(false);

        RecyclerViewClockSetting.setAdapter(clockAdapter);

        RecyclerViewClockSetting.setLayoutManager(linearLayoutManager);
    }

    private boolean isDeleteMode;

    @OnClick({R.id.iv_back, R.id.iv_share,R.id.bt_clock_back})
    public void onViewClicked(View view) {
        if(Utils.isFastClick()){return;}
        switch (view.getId()) {
            case R.id.bt_clock_back:
                finish();
                break;
            case R.id.iv_back:
                isDeleteMode=!isDeleteMode;
                ivBack.setText(isDeleteMode?getString(R.string.cancel):getString(R.string.EDIT));
                clockAdapter.enableDelete();
                break;
            case R.id.iv_share:
                addClock();
                break;
        }
    }

    private void addClock() {
        List<Clock> list = clockAdapter.getClockList();
        if (list.size() == 10) {
            showToast(getString(R.string.clock_max));
            return;
        }
        Intent intent = new Intent(this, AlarmSetActivity.class);
        intent.putExtra(KEY_CLOCK_LIST, (Serializable) list);
        startActivityForResult(intent, REQUEST_Clock);
    }

    @Override
    public void dataCallback(Map<String, String> maps, SendCmdState sendCmdState) {
        super.dataCallback(maps, sendCmdState);
        switch (sendCmdState) {
            case SET_ALARM:
//                if (isDelete) {
//                    int last=Integer.valueOf(maps.get(DeviceKey.KClockLast));
//                    if(last==238){
//                        getClockData();
//                        isDelete = false;
//                    }
//                }
                break;
        }
    }
    boolean isFinish;
    @Override
    public void dataCallback(DeviceBean deviceBean, SendCmdState sendCmdState) {
        switch (sendCmdState) {
            case GET_ALARM:
                boolean isFinish = deviceBean.isFinish();
                for (Map<String, String> map : deviceBean.getDataList()) {
                    String hour = String.format("%02d", Integer.valueOf(map.get(DeviceKey.KAlarmHour)));
                    String min = String.format("%02d", Integer.valueOf(map.get(DeviceKey.KAlarmMinter)));
                    String content = map.get(DeviceKey.KAlarmContent);
                    int clockType = Integer.parseInt(map.get(DeviceKey.KAlarmType));
                    int id = Integer.parseInt(map.get(DeviceKey.KAlarmId));
                    int enable = Integer.parseInt(map.get(DeviceKey.KAlarmEnable));
                    String week = map.get(DeviceKey.KAlarmWeekEnable);
                    final Clock clock = new Clock();
                    clock.setContent(content);
                    clock.setNumber(id);
                    clock.setEnable(enable==1);
                    clock.setHour(Integer.parseInt(hour));
                    clock.setMinute(Integer.parseInt(min));
                    clock.setType(clockType);
                    byte weekByte = 0;
                    String[] weekString = week.split("-");
                    for (int i = 0; i < 7; i++) {
                        String weekEnable = weekString[i];
                        if (weekEnable.equals("1")) {
                            weekByte += Math.pow(2, i);
                        }
                    }
                    clock.setWeek(weekByte);
                    clockAdapter.setData(weekArray, clock);
                }
                this.isFinish=isFinish;
                break;
        }
    }

    @Override
    public void onItemClick(Clock clock) {
        Intent intent = new Intent(this, AlarmSetActivity.class);
        intent.putExtra("clockid", clock.getNumber());
        intent.putExtra(KEY_CLOCK_LIST, (Serializable) clockAdapter.getClockList());
        startActivityForResult(intent, REQUEST_Clock);
    }

    boolean isDelete;

    @Override
    public void onDelete(Clock clock) {
        updateClock(clockAdapter.getClockList());
    }

    @Override
    public void onUpdate() {
        updateClock(clockAdapter.getClockList());
    }

    private void updateClock(List<Clock> clockList) {
        if(!isFinish)return;
        for(int i=0;i<clockList.size();i++){
            Clock clock=clockList.get(i);
            clock.setNumber(i);
        }
        byte[] value = clockList.size()==0?SingleDealData.deleteAllClock():SingleDealData.setClockData(clockList);
        int maxLength = MainActivity.phoneDataLength;
        if (value.length > maxLength) {
            int size = maxLength / 39;//一个包最多发的闹钟个数
            int length = size * 39;//最大闹钟数占用的字节
            int count = value.length % length == 0 ? value.length / length : value.length / length + 1;//需要多少个包来发送
            for (int i = 0; i < count; i++) {
                int end = length * (i + 1);
                int endLength = length;
                if (end >= value.length) endLength = value.length - length * i;
                byte[] data = new byte[endLength];
                System.arraycopy(value, length * i, data, 0, endLength);
                offerData(data);
            }
            offerData();
        } else {
            writeData(value);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_Clock && resultCode == RESULT_OK) {
            getClockData();
        }
    }
}
